﻿#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 9999
#define BUF_SIZE 1024
using std::cin;
using std::cout;
using std::endl;
using std::string;
void Error(const string &msg)
{
  cout << msg << " error!" << endl;
  exit(-1);
}
void Print(const string &msg)
{
  cout << msg << endl;
}
int main()
{
  // step01：创建监听套接字
  int sock_serv, sock_clnt;
  if ((sock_serv = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
    Error("socket()");
  Print("socket() ok ...");
  // step02：设置监听套接字的IP和端口号
  sockaddr_in addr_serv;
  addr_serv.sin_family = AF_INET;
  addr_serv.sin_addr.s_addr = inet_addr(SERVER_IP);
  addr_serv.sin_port = htons(SERVER_PORT);
  if (bind(sock_serv, (sockaddr *)&addr_serv, sizeof(addr_serv)) == -1)
    Error("bind()");
  Print("bind() ok ...");
  // step03:进入等待请求连接状态
  if ((listen(sock_serv, 5)) == -1)
    Error("listen()");
  Print("listen() ok ...");
  sockaddr_in addr_clnt{};
  socklen_t size_addr_clnt = sizeof(addr_clnt);
  char msg[BUF_SIZE]{0};
  char response[BUF_SIZE]{0};
  for (int i = 1; i <= 10; i++)
  {
    cout << "Client " << i << " ..." << endl;
    // step04：进入数据传输状态
    if ((sock_clnt = accept(sock_serv, (sockaddr *)&addr_clnt, &size_addr_clnt)) == -1)
      Error("accept()");
    Print("accept() ok ...");
    // step05:数据传输
    recv(sock_clnt, msg, sizeof(msg), 0);
    cout << "Message from client: " << msg << endl;
    send(sock_clnt, "ok", sizeof("ok"), 0);
    close(sock_clnt);
  }
  close(sock_serv);
  return 0;
}